package youke.home.services;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class TestAliveServices {
    private static final String API_URL = "http://api.quklive.com/cloud/open/activity/info";
    private static final String APP_KEY = "vu0klr7diqnncviq";  // 用您的实际appKey替换
    private static final String APP_SECRET = "9L4qmx3SAzT1ECN7"; // 用您的实际appSecret替换

    /**
     * 发送请求获得 new JsonNode
     */
    public JsonNode getJsonNode(Long liveId) throws IOException {

        // 设置请求头和请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 获取时间戳
        long nonce = System.currentTimeMillis();

        // 生成签名
        String content = "appKey=" + APP_KEY + "&nonce=" + nonce;
        String signature = generateSignature(content);

        // 设置请求参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appKey", APP_KEY);
        requestParams.put("nonce", nonce);
        requestParams.put("signature", signature);
        requestParams.put("id", liveId);

        // 创建请求体
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestParams, headers);;

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);

        // 处理返回结果
        JsonNode jsonNode = new ObjectMapper().readTree(response.getBody());
        System.out.println(jsonNode.toString());
        return jsonNode;
    }

    /**
     * 生成签名
     */
    private String generateSignature(String content) {
        try {
            byte[] hmacSha1 = HmacUtils.hmacSha1(APP_SECRET, content);
            return Base64.encodeBase64String(hmacSha1);
        } catch (Exception e) {
            System.err.println("签名生成失败: " + e.getMessage());
            return null;
        }
    }
}
